package com.mit.wx.controller;

import com.alibaba.fastjson.JSON;
import com.mit.wx.conf.WeixinConfiguration;
import com.mit.wx.entity.WxSourceMessage;
import com.mit.wx.parser.WxMessageParser;
import com.mit.wx.service.WxSourceMessageService;
import com.mit.wx.service.WxUserService;
import com.mit.wx.util.WechartUtil;
import com.mit.wx.wx.dto.*;
import com.mit.wx.vo.EasyUIDataGrid;
import com.mit.wx.ws.cache.WebsocketSessionCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 2018/10/9 Create by 郭文梁
 * MessageController
 * Recommend of this class
 *
 * @author 郭文梁
 * @date 2018/10/9
 */
@Slf4j
@RestController
@RequestMapping("/weixin")
public class MessageController {
    private static final String SUCCESS = "success";
    private final WeixinConfiguration weixinConfiguration;
    private final WxSourceMessageService wxSourceMessageService;
    private final WxUserService wxUserService;
    private final WebsocketSessionCache sessionCache;
    private final WxMessageParser messageParser;

    @Autowired
    public MessageController(WeixinConfiguration weixinConfiguration, WxSourceMessageService wxSourceMessageService, WxUserService wxUserService, WebsocketSessionCache sessionCache, WxMessageParser messageParser) {
        this.weixinConfiguration = weixinConfiguration;
        this.wxSourceMessageService = wxSourceMessageService;
        this.wxUserService = wxUserService;
        this.sessionCache = sessionCache;
        this.messageParser = messageParser;
    }

    /**
     * 供微信服务器验证使用
     *
     * @param signature 签名
     * @param timestamp 时间
     * @param nonce     随机
     * @param echostr   原样输出内容
     * @return response body
     */
    @GetMapping
    public String validate(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           String echostr) {
        String token = weixinConfiguration.getToken();
        log.info("signature={},timestamp={},nonce={},token={},echostr={}", signature, timestamp, nonce, token, echostr);
        if (echostr != null) {
            if (WechartUtil.checkSignature(signature, token, nonce, timestamp)) {
                return echostr;
            }
        }
        return SUCCESS;
    }

    @PostMapping
    public String onMessage(@RequestBody String postXml) {
        SourceMessage message = SourceMessage.formXML(postXml);
        log.info("message={}", message);
        if (message == null) {
            return SUCCESS;
        }
        wxUserService.saveIfNotExists(message.getFromUserName());
        wxSourceMessageService.save(WxSourceMessage.of(message));
        notifyNewMessage(message);
        TargetMessage result = messageParser.parseMessage(message);
        return result == null ? SUCCESS : result.toXML();
    }

    private void notifyNewMessage(SourceMessage message) {
        WebsocketNotifierMessage notifierMessage = new WebsocketNotifierMessage();
        notifierMessage.setOpenId(message.getFromUserName());
        notifierMessage.setMsg(message.getContent());
        sessionCache.send2AllSession(JSON.toJSONString(notifierMessage));
    }

    @GetMapping("/list")
    public List<WxSourceMessage> listMessage() {
        return wxSourceMessageService.list();
    }

    @GetMapping("/page")
    public EasyUIDataGrid<WxSourceMessage> page(int page, int size) {
        return EasyUIDataGrid.of(wxSourceMessageService.getCount(), wxSourceMessageService.list(page, size));
    }

}
